package model

import "github.com/shopspring/decimal"

// Order 订单结构体
type Order struct {
	BaseModel
	UserId       int64
	User         User          `gorm:"foreignKey:id;references:UserId" json:"-"`
	OrderedItems []OrderedItem `gorm:"forignkey:OrderId"`
	TotalPrice   decimal.Decimal
	IsCannceled  bool
}

// OrderedItem 订单项结构体
type OrderedItem struct {
	BaseModel
	Product    Product `gorm:"foreignkey:ProductId"`
	ProductId  int64
	Count      int
	OrderId    int64
	IsCanceled bool
}

func (Order) TableName() string {
	return "shopping_order"
}

func (OrderedItem) TableName() string {
	return "shopping_ordered_item"
}

// NewOrder 实例化Order
func NewOrder(uid int64, items []OrderedItem) *Order {
	totalPrice, _ := decimal.NewFromString("0.00")
	for _, item := range items {
		totalPrice = totalPrice.Add(item.Product.Price)
	}
	return &Order{
		UserId:       uid,
		OrderedItems: items,
		TotalPrice:   totalPrice,
		IsCannceled:  false,
	}
}

// NewOrderedItem 实例化订单项
func NewOrderedItem(count int, pid int64) *OrderedItem {
	return &OrderedItem{
		Count:      count,
		ProductId:  pid,
		IsCanceled: false,
	}
}
